package com.fjl.paixu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

public class PaiXun
{
	public static void main(String[] args)
	{
		collectionsPaxun();

	}
	
	
	
	private static void collectionsPaxun()
	{
		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("name", "gjk");
		map.put("id", "1");
		map.put("num", 45);
		list.add(map);

		HashMap<String, Object> map2 = new HashMap<String, Object>();
		map2.put("name", "gjk2");
		map2.put("id", "2");
		map2.put("num", 60);
		list.add(map2);

		HashMap<String, Object> map3 = new HashMap<String, Object>();
		map3.put("name", "gjk3");
		map3.put("id", "3");
		map3.put("num", 30);
		list.add(map3);

		// 打印出list中的值
		 printList(list);

		ComparatorHashMap comparator = new ComparatorHashMap();
		Collections.sort(list, comparator);
		System.out.println("after@@@@@@@@@");
		// 打印出list中的值
		 printList(list);
	}
	
	/**
	 * 打印lst
	 * @param lst
	 */
	public static void printList(List<HashMap<String, Object>> lst)
	{
		for(HashMap<String, Object> map:lst)
		{
			System.out.println(map.get("id"));
		}
	}

	public static class ComparatorHashMap implements Comparator
	{

		public int compare(Object arg0, Object arg1)
		{

			HashMap<String, Object> map = (HashMap<String, Object>) arg0;
			HashMap<String, Object> map2 = (HashMap<String, Object>) arg1;

			// 首先比较出现次数，如果相同，则比较名字
			Integer num = Integer.parseInt(map.get("num").toString());
			Integer num2 = Integer.parseInt(map2.get("num").toString());
			int flag = num2.compareTo(num);
			if (flag == 0)
			{
				return (map2.get("name").toString()).compareTo(map.get("name").toString());
			}
			else
			{
				return flag;
			}
		}
	}

}
